/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.fragment;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.StringRes;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilDate;
import com.ouertech.android.agm.lib.base.utils.UtilDevice;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.BaseUIFragment;
import com.ouertech.android.agm.lib.ui.base.FragmentTab;
import com.ouertech.android.agm.lib.ui.base.FragmentTabAdapter;
import com.ouertech.android.agm.lib.ui.base.UIOptions;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Banner;
import com.simon.mengkou.data.bean.base.Category;
import com.simon.mengkou.data.bean.base.Follow;
import com.simon.mengkou.data.bean.base.GoodTopic;
import com.simon.mengkou.data.bean.base.Image;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.SignResult;
import com.simon.mengkou.data.bean.base.Topic;
import com.simon.mengkou.data.bean.base.User;
import com.simon.mengkou.data.bean.base.WishProduct;
import com.simon.mengkou.data.bean.req.FollowReq;
import com.simon.mengkou.data.bean.req.ShareOrderLikeReq;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EBannerType;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.data.enums.EEventId;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.system.global.OuerDispatcher;
import com.simon.mengkou.ui.activity.CategoryAdapter;
import com.simon.mengkou.ui.activity.ProductDetailActivity;
import com.simon.mengkou.ui.adapter.GoodsTopicAdapter;
import com.simon.mengkou.ui.adapter.HomeBannerAdapter;
import com.simon.mengkou.ui.adapter.HomeTopicAdapter;
import com.simon.mengkou.ui.adapter.HomeVideoAdapter;
import com.simon.mengkou.ui.adapter.HotTopicAdapter;
import com.simon.mengkou.ui.adapter.ProductActivityAdapter;
import com.simon.mengkou.ui.adapter.ProductImageAdapter;
import com.simon.mengkou.ui.adapter.VideoListAdapter;
import com.simon.mengkou.ui.base.BaseSocialShareUIFragment;
import com.simon.mengkou.ui.dialog.ShareDialog;
import com.simon.mengkou.ui.dialog.SignDialog;
import com.simon.mengkou.ui.view.BaseViewPager;
import com.simon.mengkou.ui.view.CustomViewPager;
import com.simon.mengkou.ui.view.HorizontalListView;
import com.simon.mengkou.ui.view.LoopPageIndicator;
import com.simon.mengkou.ui.view.LoopViewPager;
import com.simon.mengkou.ui.view.LoopViewPagerAdapter;
import com.simon.mengkou.ui.view.MyGridView;
import com.simon.mengkou.utils.UtilOuer;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.widget.MediaController2;
import io.vov.vitamio.widget.VideoView2;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/2/29.
 * desc    : 首页
 */
public class HomeFragment extends BaseSocialShareUIFragment
        implements PullToRefreshBase.OnRefreshListener2<ListView>{
    //签到
    @Bind(R.id.home_id_sign)
    ImageButton mIbSign;
    //消息
    @Bind(R.id.home_id_message)
    ImageButton mIbMessage;

    @Bind(R.id.common_pulltorefresh_id_list)
    PullToRefreshListView mPtrView;

    //单张商品图片
    private SimpleDraweeView mSdvImage;
    //多张商品图片
    private LoopViewPager mLvpPager;
    private LoopViewPagerAdapter mPagerAdapter;
    private LoopPageIndicator mLvpIndicator;
    private HomeBannerAdapter mImageAdapter;

    private RelativeLayout mRlRcmdRoot;
    private SimpleDraweeView mSdvRcmdImage;
    private TextView mTvRcmdTitle;
    private TextView mTvRcmdPrice;
    private TextView mTvRcmdMarketPrice;
    private SimpleDraweeView mSdvHotSale;
    private SimpleDraweeView mSdvHotTopic;

    private MyGridView mMgvRcmdFollow;
    private HotTopicAdapter mHotTopicAdapter;

    private TabLayout mTlTab;

    private HomeTopicAdapter mHomeTopicAdapter;
    private String mMaxId = CstOuer.PAGE.DEFAULT_MAXID;

    private HomeVideoAdapter mHomeVideoAdapter;
    private int mPage = 0;
    private Follow mShareFollow;

    private int mPosition;
    private int mLvChildTop;
    private GoodTopic mGoodTopic;

    @Override
    protected long initOptions() {
        return UIOptions.UI_OPTIONS_SYSTEMBAR
                | UIOptions.UI_OPTIONS_APPBAR_CUSTIOM
                | UIOptions.UI_OPTIONS_CONTENT_CUSTOM;
    }


    @Override
    protected void initAppCustom() {
        setAppCustomLayout(R.layout.layout_home_header);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_pulltorefresh_list);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this, getView());

        //注册消息广播
        registerAction(CstOuer.BROADCAST_ACTION.MESSAGE_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.VIDEO_FOLLOW_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.SHARE_ORDER_LIKE_ACTION);
        registerAction(CstOuer.BROADCAST_ACTION.SHARE_ORDER_COMMENT_ACTION);

        //消息
        setMessageIcon();

        //签到
        final String currDate = UtilDate.formatDate(Calendar.getInstance(), UtilDate.FORMAT_YYYYMMDD);
        String lastDate = OuerApplication.mPreferences.getSigntime(OuerApplication.mUser.getUserId());
        if (!currDate.equals(lastDate)) {//没签到
            mIbSign.setImageResource(R.drawable.user_ic_unsign);
            userIsSign();
        } else {
            mIbSign.setImageResource(R.drawable.user_ic_signed);
        }


        int width = UtilDevice.getDevice(mActivity).getWidth();

        //头部
        View header = LayoutInflater.from(mActivity).inflate(R.layout.layout_home_list_header, null);
        mPtrView.getRefreshableView().addHeaderView(header);
        //banner
        RelativeLayout rlBannerRoot = (RelativeLayout)header.findViewById(R.id.home_id_banner_root);
        rlBannerRoot.getLayoutParams().height = (int)(width/1.67f);
        mSdvImage = (SimpleDraweeView)header.findViewById(R.id.home_id_image);
        mLvpIndicator = (LoopPageIndicator)header.findViewById(R.id.home_id_indicator);
        mLvpPager = (LoopViewPager) header.findViewById(R.id.home_id_banner);
        mLvpPager.setAutoScroll(true);

        List<Banner> banners = OuerApplication.mCacheFactory.getCache(DataCacheImpl.HomeBannerCache.class)
                .getData();
        setHomeBanner(banners);

        //今日特价
        mRlRcmdRoot = (RelativeLayout)header.findViewById(R.id.home_id_recommend_root);
        mSdvRcmdImage = (SimpleDraweeView)header.findViewById(R.id.home_id_recommend_image);
        mTvRcmdTitle = (TextView)header.findViewById(R.id.home_id_recommend_title);
        mTvRcmdPrice = (TextView)header.findViewById(R.id.home_id_recommend_price);
        mTvRcmdMarketPrice = (TextView)header.findViewById(R.id.home_id_recommend_market_price);

        Product product = OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodRecommendCache.class)
                .getData();
        setGoodsRecommend(product);

        //热销榜单
        mSdvHotSale = (SimpleDraweeView)header.findViewById(R.id.home_id_sale_image);
        List<WishProduct> datas = OuerApplication.mCacheFactory
                .getCache(DataCacheImpl.HotSaleCache.class)
                .getData();
        if(UtilList.isNotEmpty(datas)) {
            OuerApplication.mImageLoader.loadImage(mSdvHotSale, datas.get(0).getImage().getUrl());
        }

        findViewById(R.id.home_id_hot_sale_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mActivity, EEventId.HOME_TOP_PRODUCT);
                OuerDispatcher.presentHotSaleActivity(mActivity);
            }
        });

        //热门专题
        mSdvHotTopic = (SimpleDraweeView)header.findViewById(R.id.home_id_topic_image);
        mGoodTopic = OuerApplication.mCacheFactory.getCache(DataCacheImpl.GoodsTopicCache.class).getData();
        if(mGoodTopic != null) {
            OuerApplication.mImageLoader.loadImage(mSdvHotTopic, mGoodTopic.getImage().getUrl());
        }

        findViewById(R.id.home_id_hot_topic_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开商品专题
                if(mGoodTopic != null) {
                    MobclickAgent.onEvent(mActivity, EEventId.HOME_HOT_PRODUCT_TOPIC);
                    OuerDispatcher.presentGoodsTopicActivity(mActivity, mGoodTopic.getId(), mGoodTopic.getImage().getUrl());
                }
            }
        });

        //推荐关注
        mMgvRcmdFollow = (MyGridView) header.findViewById(R.id.home_id_recommend_follow);
        mHotTopicAdapter = new HotTopicAdapter(mActivity);
        mMgvRcmdFollow.setAdapter(mHotTopicAdapter);

        List<Follow> posts = OuerApplication.mCacheFactory.getCache(DataCacheImpl.HotPostCache.class)
                .getData();
        mHotTopicAdapter.setList(posts);


        //萌物专辑、精选视频
        mTlTab = (TabLayout)header.findViewById(R.id.home_id_tabs);
        TabLayout.Tab topicTab = mTlTab.newTab().setText(R.string.home_tab_topic);
        TabLayout.Tab videoTab = mTlTab.newTab().setText(R.string.home_tab_video);
        mTlTab.addTab(topicTab);
        mTlTab.addTab(videoTab);
        mTlTab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if(tab.getPosition() == 0) {
                    MobclickAgent.onEvent(mActivity, EEventId.HOME_TAB_TOPIC);
                    mPtrView.setAdapter(mHomeTopicAdapter);
                } else {
                    MobclickAgent.onEvent(mActivity, EEventId.HOME_TAB_VIDEO);
                    mPtrView.setAdapter(mHomeVideoAdapter);
                }

                mPtrView.getRefreshableView().setSelectionFromTop(mPosition, mLvChildTop);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //萌物专题
        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
        mPtrView.setTag(false);

        mPtrView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    mPosition = mPtrView.getRefreshableView().getFirstVisiblePosition();
                    View v = mPtrView.getRefreshableView().getChildAt(0);
                    mLvChildTop = (v == null) ? 0 : v.getTop();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        mHomeTopicAdapter = new HomeTopicAdapter(mActivity);
        mPtrView.setAdapter(mHomeTopicAdapter);
        List<Topic> homeTopics = OuerApplication.mCacheFactory.getCache(DataCacheImpl.HomeTopicCache.class).getData();
        if(UtilList.isNotEmpty(homeTopics)) {
            mPtrView.setTag(true);
            mHomeTopicAdapter.setList(homeTopics);
        }

        //精选视频
        mHomeVideoAdapter = new HomeVideoAdapter(mActivity, this);
        List<Follow> videos = OuerApplication.mCacheFactory.getCache(DataCacheImpl.HotVideoCache.class).getData();
        mHomeVideoAdapter.setList(videos);

        setOnRetryListener(new OnRetryListener() {
            @Override
            public void onRetry() {
                homeBanner();
                goodsRecommend();
                hotPost();
                homeTopic(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
                homeVideo(0, EDirection.REFRESH);
            }
        });

        homeBanner();
        goodsRecommend();
        hotPost();
        hotSales();
        goodsTopic();
        homeTopic(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
        homeVideo(0, EDirection.REFRESH);
    }


    @Override
    protected void onReceive(Intent intent) {
        super.onReceive(intent);
        //消息推送广播
        String action = intent.getAction();
        if(CstOuer.BROADCAST_ACTION.MESSAGE_ACTION.equals(action)) {
            setMessageIcon();
        } else if(CstOuer.BROADCAST_ACTION.FOLLOW_ACTION.equals(intent.getAction())) {
            //更新关注状态
            FollowReq req = (FollowReq) intent.getSerializableExtra(CstOuer.KEY.FOLLOW);
            List<Follow> datas = mHomeVideoAdapter.getData();
            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    User user = follow.getUser();
                    if(user.getUserId().equals(req.getTargetId())) {
                        user.setInterested(req.isChecked());
                    }
                }
            }

            mHomeVideoAdapter.notifyDataSetChanged();
        } else if(CstOuer.BROADCAST_ACTION.VIDEO_FOLLOW_ACTION.equals(intent.getAction())) {
            String id =  intent.getStringExtra(CstOuer.KEY.ID);
            List<Follow> datas = mHomeVideoAdapter.getData();

            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(id)) {
                        follow.setCollected(true);
                    }
                }
            }

        } else if(CstOuer.BROADCAST_ACTION.SHARE_ORDER_LIKE_ACTION.equals(intent.getAction())) {
            ShareOrderLikeReq req = (ShareOrderLikeReq) intent.getSerializableExtra(CstOuer.KEY.LIKE);
            List<Follow> datas = mHomeVideoAdapter.getData();
            boolean flag = false;
            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(req.getId())) {
                        follow.setLiked(req.isCheck());
                        if(req.isCheck()) {
                            follow.setFaverNum(follow.getFaverNum() + 1);
                        } else {
                            follow.setFaverNum(follow.getFaverNum() - 1);
                        }
                        flag = true;
                    }
                }
            }

            if(flag) {
                mHomeVideoAdapter.notifyDataSetChanged();
            }
        }
        else if(CstOuer.BROADCAST_ACTION.SHARE_ORDER_COMMENT_ACTION.equals(intent.getAction())) {
            String id =  intent.getStringExtra(CstOuer.KEY.ID);
            List<Follow> datas = mHomeVideoAdapter.getData();

            if(UtilList.isNotEmpty(datas)) {
                for(Follow follow : datas) {
                    if(follow.getId().equals(id)) {
                        follow.setCommentNum(follow.getCommentNum() + 1);

                    }
                }
            }

        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        //下拉刷新
        if(mTlTab.getSelectedTabPosition() == 0) {
            homeTopic(CstOuer.PAGE.DEFAULT_MAXID, EDirection.REFRESH);
        } else {
            homeVideo(0, EDirection.REFRESH);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //上拉加载更多
        if(mTlTab.getSelectedTabPosition() == 0) {
            homeTopic(mMaxId, EDirection.LOADMORE);
        } else {
            homeVideo(mPage + 1, EDirection.LOADMORE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        mLvpPager.startScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        mLvpPager.cancelScroll();
    }


    /**
     * 打开扭蛋拉新界面
     */
    @OnClick(R.id.home_id_sign)
    public void sign() {
        userSign();
    }

    /**
     * 打开消息界面
     */
    @OnClick(R.id.home_id_message)
    public void presentMessage() {
        OuerApplication.mPreferences.setMessage(false);
        setMessageIcon();

        OuerDispatcher.presentMessageActivity(mActivity);
    }

    /**
     * 设置消息图标
     */
    private void setMessageIcon() {
        //有未读消息
        if(OuerApplication.mPreferences.getMessage()) {
            mIbMessage.setImageResource(R.drawable.home_ic_message_pressed);
        } else {
            mIbMessage.setImageResource(R.drawable.home_ic_message_normal);
        }
    }


    /**
     * 用户是否已签到
     */
    private void userIsSign() {
        AgnettyFuture future = OuerApplication.mOuerFuture.userIsSign(OuerApplication.mUser.getUserId(),
                new OuerFutureListener(mActivity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        SignResult data = (SignResult)result.getAttach();
                        if(data.isResult()) {
                            OuerApplication.mPreferences.setSigntime(OuerApplication.mUser.getUserId(),
                                    UtilDate.formatDate(Calendar.getInstance(), UtilDate.FORMAT_YYYYMMDD));
                            mIbSign.setImageResource(R.drawable.user_ic_signed);
                        }
                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 用户签到
     */
    private void userSign() {
        final String currDate = UtilDate.formatDate(Calendar.getInstance(), UtilDate.FORMAT_YYYYMMDD);
        String lastDate = OuerApplication.mPreferences.getSigntime(OuerApplication.mUser.getUserId());
        if (!currDate.equals(lastDate)) {
            final AgnettyFuture future = OuerApplication.mOuerFuture.userSign(OuerApplication.mUser.getUserId(),
                    new OuerFutureListener(mActivity) {
                        @Override
                        public void onStart(AgnettyResult result) {
                            super.onStart(result);
                            setWaitingDialog(true);
                        }

                        @Override
                        public void onComplete(AgnettyResult result) {
                            super.onComplete(result);
                            setWaitingDialog(false);
                            UtilOuer.toast(mActivity, R.string.user_sign_success);
                            mIbSign.setImageResource(R.drawable.user_ic_signed);
                            OuerApplication.mPreferences.setSigntime(
                                    OuerApplication.mUser.getUserId(),
                                    UtilDate.formatDate(Calendar.getInstance(), UtilDate.FORMAT_YYYYMMDD));
//                            userSignList();
                            userInfo();
                        }

                        @Override
                        public void onException(AgnettyResult result) {
                            super.onException(result);
                            setWaitingDialog(false);
                            UtilOuer.showExceptionToast(mActivity, result, R.string.user_sign_failure);
                        }

                        @Override
                        public void onNetUnavaiable(AgnettyResult result) {
                            super.onNetUnavaiable(result);
                            setWaitingDialog(false);
                        }
                    });

            attachDestroyFutures(future);
        } else {
            UtilOuer.toast(mActivity, R.string.user_sign_signed);
        }
    }

    /**
     * 用户签到列表
     */
    private void userSignList() {
        final AgnettyFuture future = OuerApplication.mOuerFuture.userSignList(
                new OuerFutureListener(mActivity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        SignDialog dialog = new SignDialog(mActivity);
                        dialog.show();
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                });

        attachDestroyFutures(future);
    }

    /**
     * 用户信息
     */
    private void userInfo() {
        final AgnettyFuture future = OuerApplication.mOuerFuture.getUserInfo(OuerApplication.mUser.getUserId(),
                new OuerFutureListener(mActivity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        User user = (User) result.getAttach();
                        OuerApplication.mUser.setIntegral(user.getIntegral());
                        OuerDispatcher.sendUserSignBroadcast(mActivity);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                });

        attachDestroyFutures(future);
    }


    /**
     * 首页Banner列表
     */
    private void homeBanner() {
        AgnettyFuture future = OuerApplication.mOuerFuture.homeBanner(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        final List<Banner> datas = (List<Banner>) result.getAttach();
                        OuerApplication.mCacheFactory.getCache(DataCacheImpl.HomeBannerCache.class)
                                .save(datas);
                        setHomeBanner(datas);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }

    private void setHomeBanner(List<Banner> datas) {
        if(UtilList.isEmpty(datas)) {
            return;
        }

        if(UtilList.getCount(datas) == 1) {
            final Banner data = datas.get(0);
            OuerApplication.mImageLoader.loadImage(mSdvImage, data.getImage().getUrl());
            mSdvImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(mActivity, EEventId.HOME_BANNER);
                    switch (data.getType()) {
                        case EBannerType.BANNER_ACTIVITY:
                            OuerDispatcher.presentWebActivity(mActivity, data.getRelateId(), null);
                            break;
                        case EBannerType.BANNER_PRODUCT:
                            OuerDispatcher.presentProductDetailActivity(mActivity, data.getRelateId());
                            break;
                        case EBannerType.BANNER_SHARE_ORDER:
                            OuerDispatcher.presentShareOrderDetailActivity(mActivity, data.getRelateId());
                            break;
                        case EBannerType.BANNER_TOPIC:
                            OuerDispatcher.presentWebTopicDetailActivity(mActivity, data.getRelateId());
                            break;
                        default:
                            break;
                    }
                }
            });
        } else {
            mLvpIndicator.initIndicator(0,
                    datas.size(),
                    R.drawable.common_ic_indicator_dot_normal,
                    R.drawable.common_ic_indicator_dot_focus);

            mImageAdapter = new HomeBannerAdapter(mActivity, datas);
            mPagerAdapter = new LoopViewPagerAdapter(mImageAdapter);
            mLvpPager.setInfinateAdapter(mPagerAdapter);

            mLvpPager.setOnPageChangeListener(new BannerPageChangeListener(datas.size()));
        }
    }


    /**
     * 推荐商品
     */
    private void goodsRecommend() {
        AgnettyFuture future = OuerApplication.mOuerFuture.goodsRecommend(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        Product product = (Product) result.getAttach();
                        OuerApplication.mCacheFactory.getCache(DataCacheImpl.MallGoodRecommendCache.class)
                                .save(product);
                        setGoodsRecommend(product);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }


    private void setGoodsRecommend(final Product product) {
        if(product == null) {
            return;
        }

        //图片
        OuerApplication.mImageLoader.loadImage(mSdvRcmdImage, product.getImageArray().get(0).getUrl());
        //标题
        mTvRcmdTitle.setText(product.getTitle());
        //价格
        mTvRcmdPrice.setText(getString(R.string.common_price,
                UtilOuer.formatPrice(product.getPrice())));
        //原价
        mTvRcmdMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中划线
        mTvRcmdMarketPrice.getPaint().setAntiAlias(true);
        mTvRcmdMarketPrice.setText(getString(R.string.buy_recommend_market_price,
                UtilOuer.formatPrice(product.getMarketPrice())));

        mRlRcmdRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(mActivity, EEventId.HOME_TODAY_PRODUCT);
                OuerDispatcher.presentProductDetailActivity(mActivity, product.getId());
            }
        });
    }


    /**
     * 热门帖子
     */
    private void hotPost() {
        AgnettyFuture future = OuerApplication.mOuerFuture.hotPost(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<Follow> datas = (List<Follow>) result.getAttach();
                        OuerApplication.mCacheFactory.getCache(DataCacheImpl.HotPostCache.class)
                                .save(datas);
                        mHotTopicAdapter.setList(datas);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }


    /**
     * 萌物专题
     * @param maxId
     * @param direction
     */
    private void homeTopic(final String maxId, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.getHomeTopicList(
                maxId, CstOuer.PAGE.DEFAULT_MINID, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(mActivity){

                    public void onStart(AgnettyResult result) {
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setLoading(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            mPtrView.setTag(true);
                            setLoading(false);
                        } else {
                            mPtrView.onRefreshComplete();
                        }

                        List<Topic> datas = (List<Topic>) result.getAttach();

                        if(direction == EDirection.REFRESH) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.HomeTopicCache.class).save(datas);
                            int count = UtilList.getCount(datas);
                            //设置最新的max id
                            if(count != 0) {
                                mMaxId = datas.get(count - 1).getId();
                            }

                            mHomeTopicAdapter.setList(datas);
                        } else {
                            int count = UtilList.getCount(datas);
                            //设置最新的max id
                            if(count != 0) {
                                mMaxId = datas.get(count - 1).getId();
                            }

                            mHomeTopicAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }
                });

        attachDestroyFutures(future);
    }


    /**
     * 精选视频
     * @param page
     * @param direction
     */
    private void homeVideo(int page, final int direction) {
        //调用商品搜索接口
        AgnettyFuture future = OuerApplication.mOuerFuture.homeVideo(
                page, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(mActivity){

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mPtrView.onRefreshComplete();
                        List<Follow> datas = (List<Follow>) result.getAttach();

                        if(direction == EDirection.REFRESH) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.HotVideoCache.class).save(datas);
                            mPage = 0;
                            mHomeVideoAdapter.setList(datas);
                        } else {
                            mPage++;
                            mHomeVideoAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        mPtrView.onRefreshComplete();
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        mPtrView.onRefreshComplete();
                    }
                });

        attachDestroyFutures(future);
    }


    /**
     * 获取新粉丝消息
     */
    private void hotSales() {
        AgnettyFuture future = OuerApplication.mOuerFuture.hotSales(
                0, 1,
                new OuerFutureListener(mActivity){


                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<WishProduct> datas = (List<WishProduct>) result.getAttach();
                        if(UtilList.isNotEmpty(datas)) {
                            OuerApplication.mImageLoader.loadImage(mSdvHotSale, datas.get(0).getImage().getUrl());
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
//                        super.onNetUnavaiable(result);

                    }
                });

        attachDestroyFutures(future);
    }


    /**
     * 首页商品专题
     */
    private void goodsTopic() {
        AgnettyFuture future = OuerApplication.mOuerFuture.newhotGoodsTopic(
                new OuerFutureListener(mActivity) {

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mGoodTopic = (GoodTopic) result.getAttach();
                        if(mGoodTopic != null) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.GoodsTopicCache.class)
                                    .save(mGoodTopic);
                            OuerApplication.mImageLoader.loadImage(mSdvHotTopic, mGoodTopic.getImage().getUrl());
                        }
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {

                    }
                }
        );

        attachDestroyFutures(future);
    }



    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.share_id_qq://分享到qq
                shareOrder(SHARE_MEDIA.QQ, mShareFollow);
                break;
            case R.id.share_id_wechat://分享到微信
                shareOrder(SHARE_MEDIA.WEIXIN, mShareFollow);
                break;
            case R.id.share_id_sina://分享到新浪
                shareOrder(SHARE_MEDIA.SINA, mShareFollow);
                break;
            case R.id.share_id_qzone://分享qq空间
                shareOrder(SHARE_MEDIA.QZONE, mShareFollow);
                break;
            case R.id.share_id_circle://分享微信朋友圈
                shareOrder(SHARE_MEDIA.WEIXIN_CIRCLE, mShareFollow);
                break;
        }
    }

    /**
     * 分享
     * @param platform
     */
    private void shareOrder(SHARE_MEDIA platform, Follow follow) {
        if(UtilList.isNotEmpty(follow.getImageArray())) {
            share(platform, getString(R.string.app_name),
                    follow.getContent(), follow.getShareUrl(), follow.getImageArray().get(0).getUrl());
        } else {
            share(platform, getString(R.string.app_name),
                    follow.getContent(), follow.getShareUrl(), follow.getVideoCover());
        }
    }

    /**
     * 显示分享对话框
     * @param follow
     */
    public void showShareDialog(Follow follow) {
        mShareFollow = follow;
        ShareDialog dialog = new ShareDialog(mActivity, this);
        dialog.showAtLocation(mPtrView, Gravity.CENTER, 0, 0);
    }

    /**
     *
     * @author Zhenshui.Xia
     *
     */
    private class BannerPageChangeListener implements BaseViewPager.OnPageChangeListener {
        //
        public static final int SCROLL_STATE_IDLE = 0;
        //
        public static final int SCROLL_STATE_DRAGGING = 1;
        //
        public static final int SCROLL_STATE_SETTLING = 2;

        private int mSize;

        public BannerPageChangeListener(int size) {
            this.mSize = size;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case SCROLL_STATE_IDLE:
                    break;

                case SCROLL_STATE_DRAGGING:
                    break;

                case SCROLL_STATE_SETTLING:
                    break;
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            int index = position % mSize;
            mLvpIndicator.refreshIndicator(index);

        }

    }

}
